// 覆盖图表
var coverChart = echarts.init(document.getElementById('coverChart'));
var coverOption = {
  tooltip: {
    formatter: "{a}<br/>{b}",
    extraCssText: "text-align:center;padding:4px 10px;"
  },
  visualMap: {
      show:false,
      min: 0,
      max: 1800,
      inRange: {
          color: ['#fdf2e2', '#ffaa23']
      }
  },
  geo: {
      map: 'china',
      roam: false,
      label: {
          normal: { show: false },
          emphasis:{ show:false }
      },
      itemStyle: {
          normal:{
              borderColor: '#fff'
          },
          emphasis:{
              areaColor: "#ffaa23",
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              shadowBlur: 15,
              borderWidth: 0,
              shadowColor: 'rgba(255, 170, 35, 0.5)'
          }
      },
      top:0,
      bottom:0
  },
  series : [
     {
         type: 'scatter',
         coordinateSystem: 'geo'
      },
      {
          name: '参赛地区',
          type: 'map',
          geoIndex: 0,
          data:[
              {name: '广东', value: 1705},
              {name: '陕西', value: 554},
              {name: '北京', value: 403},
              {name: '四川', value: 303},
              {name: '甘肃', value: 197	},
              {name: '上海', value: 141	},
              {name: '江苏', value: 135	},
              {name: '湖北', value: 119},
              {name: '浙江', value: 104},
              {name: '河南', value: 89},
              {name: '重庆', value: 87},
              {name: '辽宁', value: 57},
              {name: '山东', value: 50},
              {name: '湖南', value: 50},
              {name: '澳门', value: 49},
              {name: '天津', value: 41},
              {name: '河北', value: 41},
              {name: '福建', value: 37},
              {name: '江西', value: 32},
              {name: '安徽', value: 29},
              {name: '香港', value: 27},
              {name: '吉林', value: 21},
              {name: '黑龙江', value: 19},
              {name: '云南', value: 13},
              {name: '广西', value: 12},
              {name: '山西', value: 11},
              {name: '海南', value: 8},
              {name: '新疆', value: 7},
              {name: '台湾', value: 5},
              {name: '贵州', value: 5},
              {name: '宁夏', value: 2},
              {name: '内蒙古', value: 1},
              {name: '南海诸岛', value: 0}
          ]
      }
  ]
};

// 复赛信息
var userEmail = "",userCode = "";
// 文件状态
var answerfile = "";
var thinkfile = "";
var codefile = "";
var listfile = "";

// 配置运行结果上传控件
var answerSize = 10*1024*1024,
    answerType = 'txt',
    answerMimeTypes = 'text/plain';
var answerUp = WebUploader.create({
    swf: '/webuploader/Uploader.swf',
    server: 'http://localhost/upload.php',  // 文件接收服务端。
    pick: '#answerUp',   // 选择文件的按钮。
    accept: {
      extensions: answerType,
      mimeTypes: answerMimeTypes   //限制只能txt文件
    }, //限制只能txt格式
    threads: 1,  //只允许上传1个
    fileVal: "answer",  //文件上传域的name
    fileSingleSizeLimit: answerSize  //限制5M
});

// 配置解题思路上传控件
var thinkSize = 50*1024*1024,
    thinkType = 'doc,docx',
    thinkMimeTypes = 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document';
var thinkUp = WebUploader.create({
    swf: '/webuploader/Uploader.swf',
    server: 'http://localhost/upload.php',
    pick: '#thinkUp',
    accept: {
      extensions: thinkType,
      mimeTypes: thinkMimeTypes
    },
    threads: 1,
    fileVal: "think",
    fileSingleSizeLimit: thinkSize
});

// 配置相关代码上传控件
var codeSize = 100*1024*1024,
    codeType = 'rar,zip',
    codeMimeTypes = '';
var codeUp = WebUploader.create({
    swf: '/webuploader/Uploader.swf',
    server: 'http://localhost/upload.php',
    pick: '#codeUp',
    accept: {
      extensions: codeType,
      mimeTypes: codeMimeTypes
    },
    threads: 1,
    fileVal: "code",
    fileSingleSizeLimit: codeSize
});

// 配置排名表上传控件
var listSize = 100*1024*1024,
    listType = 'xls,xlsx',
    listMimeTypes = 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
var listUp = WebUploader.create({
    swf: '/webuploader/Uploader.swf',
    server: 'http://localhost/upload.php',
    pick: '#listUp',
    accept: {
      extensions: listType,
      mimeTypes: listMimeTypes
    },
    threads: 1,
    fileVal: "list",
    fileSingleSizeLimit: listSize
});



$(function(){

  // ie9及以上才加载代码雨
  if(+[1,]){
    $(document).ready(function() {
      var width = coderain.width = screen.availWidth ;
      var height = coderain.height = screen.availHeight;
      var yPositions = Array(300).join(0).split('');
      var ctx = coderain.getContext('2d');
      var draw = function() {
        ctx.fillStyle = 'rgba(0,0,0,.05)';
        ctx.fillRect(0, 0, width, height);
        ctx.fillStyle = '#007d80';/*代码颜色*/
        ctx.font = '10pt Georgia';
        yPositions.map(function(y, index) {
             text = String.fromCharCode(1e2 + Math.random() * 330);
             x = (index * 10) + 10;
             coderain.getContext('2d').fillText(text, x, y);
             if (y > Math.random() * 1e4) {
                yPositions[index] = 0;
             } else {
                yPositions[index] = y + 10;
             }
        });
      };
      RunMatrix();
      function RunMatrix() {
        Game_Interval = setInterval(draw,30);
      }
    });
  }
  else {
    $(".main-box").attr("style","overflow-y:hidden");
    $(".main-box").append(
      '<div class="low-tip"><div></div><p>'+
      '开玩笑吧，竟然使用ie低版本访问。。/(ㄒoㄒ)/~~<br/>请使用ie9或以上版本，或者使用高级浏览器，例如 谷歌~'+
      '</p></div>'
    )
  }

  // 活动日期及说明
  $(document).on("mouseenter",".date-step li",function(){
    var $this = $(this);
    var step = $this.index();
    var leftPx = "-" + 940*step + "px";
    $(".date-step li").removeClass("active");
    $this.addClass("active");
    $(".explain-step").css("left",leftPx);
  });

  //手机版活动说明
  $(".substep-title").click(function(){
    var $this = $(this);
    $(".substep-title").removeClass("active");
    $this.addClass("active");
    $(".substep-content").slideUp();
    $this.siblings(".substep-content").slideDown();
  });

  // 检测在微信点击的下载按钮
  var dlBtn = $('#downQuestionImg');
  weixinTip(dlBtn);

  // 绘制图表
  coverChart.setOption(coverOption);

  //展开复赛模块
  $("[name='showSecond']").click(function(){
    $('.main-box').animate({scrollTop:0}, 100,function(){
      $(".main-box").addClass("secondshow");
      $(".banner-box .banner-title-box").removeClass("beBig").addClass("beSmall");
      setTimeout(function(){
        $(".banner-box .big-title img").css("width","100%");
      },400);
    });
  });

  //返回首页
  $("#backFirst").click(function(){
    $(".main-box").removeClass("secondshow");
    $(".banner-box .banner-title-box").removeClass("beSmall").addClass("beBig");
    $(".banner-box .big-title img").css("width","auto");
  });

  // 验证邮箱&识别码
  $("#verifyId").click(function(){
    var $error = $(".validate-row .error");
    userEmail = $("[name='userEmail']").val();
    userCode = $("[name='userCode']").val();
    if(userEmail == "" || userCode==""){
      $error.text("邮箱、验证码不能为空");
      return false
    }
    //todo 判断邮箱及验证码是否匹配成功
    $.ajax({
        type: "post",
        url: "http://localhost/code.php",
        data: {
          user_code: userCode,
          user_email: userEmail
        },
        dataType: "json",
        success: function(result){
          console.log(result);
          if(result.status != 200){
            $error.text("验证不通过，请检查下邮箱及识别码");
            return false
          }
          //显示提交模块
          $error.text("");
          resetUserinfo();
          $(".finals-ul").css("left","-100%");
          if(!result.admin) $("#listBox").remove();
          $(".answer-box").show();
          answerUp.options.formData = {
            "fileType" : "answer",
            "user_email" : userEmail,
            "user_code" : userCode,
          };
          thinkUp.options.formData = {
            "fileType" : "think",
            "user_email" : userEmail,
            "user_code" : userCode,
          };
          codeUp.options.formData = {
            "fileType" : "code",
            "user_email" : userEmail,
            "user_code" : userCode,
          };
          listUp.options.formData = {
            "fileType" : "list",
            "user_email" : userEmail,
            "user_code" : userCode,
          };
          // 显示上传模块
          $(".upload-box").animate({
            "opacity":"1"
          },1000);
        }
    })
  });

  // 初始化上传插件
  uploadInit();

  // 触发上传控件
  $(document).on("click",".upload-hidebtn",function(){
    $(this).closest("li").find(".upload-hidden [type='file']").click();
  });

  // 上传答案
  $(document).on("click","#uploadAllFiles",function(){
    if(answerfile!="" || thinkfile!="" || codefile!="" || listfile!=""){
      $(".upload-allFiles span").empty();
      answerUp.upload();
      thinkUp.upload();
      codeUp.upload();
      listUp.upload();
    }
    var codelink = $("[name='fileLink']").val();
    if(codelink != ""){
      //todo 提交链接
      $(".codelink-tip").addClass("success").html("代码链接：提交成功！");
      $(".codelink-box .upload-current").hide().find("textarea").val("");
      $(".codelink-box .upload-before").show();
    }
  });

  // 重置上传控件
  $(document).on("click","#resetUpload",function(){
    if(answerfile != "") {
      answerUp.cancelFile(answerfile);
      answerUp.removeFile(answerfile);
      answerfile = "";
    }
    if(thinkfile != "") {
      thinkUp.cancelFile(thinkfile);
      thinkUp.removeFile(thinkfile);
      thinkfile = "";
    }
    if(codefile != "") {
      codeUp.cancelFile(codefile);
      codeUp.removeFile(codefile);
      codefile = "";
    }
    if(listfile != "") {
      listUp.cancelFile(listfile);
      listUp.removeFile(listfile);
      listfile = "";
    }
    $(".upload-before").show();
    $(".upload-current").hide();
    $(".upload-current .file-title p").empty();
    $(".progress-bar").css("width","0");
    $(".codelink-box textarea").val("");
    $(".upload-allFiles span").removeClass("success error").empty();
  });

  // 刷新个人信息
  $(document).on("click",".refreshUserinfo",function(){
    resetUserinfo();
  });

  // 鼠标经过效果
  $(document).on("mouseenter",".upload-check-box .upload-before",function(){
    $(this).closest("li").css("background-image","url(image/upload_icon2.png)");
  })
  .on("mouseleave",".upload-check-box .upload-before",function(){
    $(this).closest("li").css("background-image","url(image/upload_icon.png)");
  })

})



// 添加提示
function addTip(result){
  var object = result.object,
      state = result.state,
      text = result.text;
  console.log(object,state,text);
  $("."+object+"-tip").attr("class",object+"-tip "+state).html(text);
}

// 返回上传前
function backUpload(object){
  resetUserinfo();
  $("#"+object+"Box .upload-check-box .upload-before").show();
  $("#"+object+"Box .upload-check-box .upload-current").hide();
  $("#"+object+"Box .upload-check-box .progress-bar").css("width","0");
  if(object == "answer") answerUp.reset();
  if(object == "think") thinkUp.reset();
  if(object == "code") codeUp.reset();
  if(object == "list") listUp.reset();
}

// 上传插件初始化
function uploadInit(){
  // 答案上传
  answerUp.on('beforeFileQueued', function( file ){
    if(answerType.indexOf(file.ext) != -1 && file.size <= answerSize){
      if(answerfile != "") answerUp.removeFile(answerfile);
      $("#answerBox .upload-check-box .upload-before").hide();
      $("#answerBox .upload-check-box .upload-current").show().addClass("upload-hidebtn");
      answerfile = file;
    }
    else{
      addTip({
        object:"answer",
        state:"error",
        text:"运行结果：请上传“txt”格式文件，并控制大小在10MB以内。"
      });
    }
  })
  .on('fileQueued', function( file ) {  // 加载文件时显示
      $("#answerFilename").text(file.name);
      addTip({
        object:"answer",
        state:"",
        text:"运行结果：等待提交..."
      });
  })
  .on( 'uploadProgress', function( file, percentage ) {  //更新进度条
      $("#answerBox .upload-check-box .upload-current").removeClass("upload-hidebtn");
      $("#answerBox .progress-bar").css( 'width', percentage * 100 + '%' );
      addTip({
        object:"answer",
        state:"success",
        text:"运行结果：正在提交..."
      });
  })
  .on( 'uploadSuccess', function( file ) {  // 上传成功
      addTip({
        object:"answer",
        state:"success",
        text:"运行结果：提交成功！"
      });
  })
  .on( 'uploadError', function( file ) {  // 上传失败
      addTip({
        object:"answer",
        state:"error",
        text:"运行结果：提交失败！"
      });
  })
  .on( 'uploadComplete', function( file ) {  // 上传完成
      answerUp.removeFile(answerfile);
      answerfile="";
      // setTimeout(function(){
      //     backUpload("answer");
      // },2000);
  });

  // 解题思路上传
  thinkUp.on('beforeFileQueued', function( file ){
    if(thinkType.indexOf(file.ext) != -1 && file.size <= thinkSize){
      if(thinkfile != "") thinkUp.removeFile(thinkfile);
      $("#thinkBox .upload-check-box .upload-before").hide();
      $("#thinkBox .upload-check-box .upload-current").show().addClass("upload-hidebtn");
      thinkfile = file;
    }
    else{
      addTip({
        object:"think",
        state:"error",
        text:"解题思路：请上传“doc”或“docx”格式文件，并控制大小在50MB以内。"
      });
    }
  })
  .on('fileQueued', function( file ) {
      $("#thinkFilename").text(file.name);
      addTip({
        object:"think",
        state:"",
        text:"解题思路：等待提交..."
      });
  })
  .on( 'uploadProgress', function( file, percentage ) {
      $("#thinkBox .upload-check-box .upload-current").removeClass("upload-hidebtn");
      $("#thinkBox .progress-bar").css( 'width', percentage * 100 + '%' );
      addTip({
        object:"think",
        state:"success",
        text:"解题思路：正在提交..."
      });
  })
  .on( 'uploadSuccess', function( file ) {
      addTip({
        object:"think",
        state:"success",
        text:"解题思路：提交成功！"
      });
  })
  .on( 'uploadError', function( file ) {
      addTip({
        object:"think",
        state:"error",
        text:"解题思路：提交失败！"
      });
  })
  .on( 'uploadComplete', function( file ) {
      thinkUp.removeFile(thinkfile);
      thinkfile="";
      // setTimeout(function(){
      //     backUpload("think");
      // },2000);
  });

  // 相关代码上传
  codeUp.on('beforeFileQueued', function( file ){
    if(codeType.indexOf(file.ext) != -1 && file.size <= codeSize){
      if(codefile != "") codeUp.removeFile(codefile);
      $("#codeBox .upload-check-box .upload-before").hide();
      $("#codeBox .upload-check-box .upload-current").show().addClass("upload-hidebtn");
      codefile = file;
    }
    else{
      addTip({
        object:"code",
        state:"error",
        text:"相关代码：请上传“rar”或“zip”格式文件，并控制大小在100MB以内；如果代码体积较大，建议使用<a href='javascript:void(0)' class='linktoshare'>分享文件链接</a>的方式提交代码。"
      });
    }
  })
  .on('fileQueued', function( file ) {
      $("#codeFilename").text(file.name);
      addTip({
        object:"code",
        state:"",
        text:"相关代码：等待提交..."
      });
  })
  .on( 'uploadProgress', function( file, percentage ) {
      $("#codeBox .upload-check-box .upload-current").removeClass("upload-hidebtn");
      $("#codeBox .progress-bar").css( 'width', percentage * 100 + '%' );
      addTip({
        object:"code",
        state:"success",
        text:"相关代码：正在提交..."
      });
  })
  .on( 'uploadSuccess', function( file ) {
      addTip({
        object:"code",
        state:"success",
        text:"相关代码：提交成功！"
      });
  })
  .on( 'uploadError', function( file ) {
      addTip({
        object:"code",
        state:"error",
        text:"相关代码：提交失败！"
      });
  })
  .on( 'uploadComplete', function( file ) {
      codeUp.removeFile(codefile);
      codefile="";
      // setTimeout(function(){
      //     backUpload("code");
      // },2000);
  });

  // 排行榜上传
  listUp.on('beforeFileQueued', function( file ){
    if(listType.indexOf(file.ext) != -1 && file.size <= listSize){
      if(listfile != "") listUp.removeFile(listfile);
      $("#listBox .upload-check-box .upload-before").hide();
      $("#listBox .upload-check-box .upload-current").show().addClass("upload-hidebtn");
      listfile = file;
    }
    else{
      addTip({
        object:"list",
        state:"error",
        text:"排行榜：请上传“xls”或“xlsx”格式文件，并控制大小在100MB以内。"
      });
    }
  })
  .on('fileQueued', function( file ) {
      $("#listFilename").text(file.name);
      addTip({
        object:"list",
        state:"",
        text:"排行榜：等待提交..."
      });
  })
  .on( 'uploadProgress', function( file, percentage ) {
      $("#listBox .upload-check-box .upload-current").removeClass("upload-hidebtn");
      $("#listBox .progress-bar").css( 'width', percentage * 100 + '%' );
      addTip({
        object:"list",
        state:"success",
        text:"排行榜：正在提交..."
      });
  })
  .on( 'uploadSuccess', function( file ) {
      addTip({
        object:"list",
        state:"success",
        text:"排行榜：提交成功！"
      });
  })
  .on( 'uploadError', function( file ) {
      addTip({
        object:"list",
        state:"error",
        text:"排行榜：提交失败！"
      });
  })
  .on( 'uploadComplete', function( file ) {
      listUp.removeFile(listfile);
      listfile="";
      // setTimeout(function(){
      //     backUpload("list");
      // },2000);
  });

  // 代码链接
  $(document).on("click",".codelink-box .upload-before,.linktoshare",function(){
    $(".codelink-box .upload-before").hide();
    $(".codelink-box .upload-current").show().find("textarea").empty().focus();
    $(".codelink-tip").attr("class","codelink-tip").empty();
  });
}

// 填充用户信息
function resetUserinfo(){
  var $userInfo = $("#userinfoBox");
  //todo 获取个人信息
  $userInfo.empty().append(
    '<p>'+
      '<span>'+userEmail+'</span>'+
      ' 您好！'+
    '</p>'+
    '<ul>'+
      '<li style="margin-bottom:16px;">'+
        '当前排名：<span class="main-text">1</span>'+
      '</li>'+
      '<li>'+
        '最优成绩：<span >98.22</span>'+
      '</li>'+
      '<li>'+
        '上次成绩：<span >91.23</span>'+
      '</li>'+
      '<li style="margin-bottom:16px;">'+
        '提交次数：<span >5</span>'+
      '</li>'+
      '<li>'+
        '运行结果：<span >已提交</span>'+
      '</li>'+
      '<li>'+
        '解题思路：<span >已提交</span>'+
      '</li>'+
      '<li>'+
        '相关代码：<span class="red-text">未提交</span>'+
      '</li>'+
    '</ul>'
    // +'<input type="button" class="refreshUserinfo" value="刷新信息" />'
  );
}

//微信检测
function weixinTip(ele){
	var ua = navigator.userAgent;
	var isWeixin = !!/MicroMessenger/i.test(ua);
	if(isWeixin){
    $(ele).click(function(){
      	window.event? window.event.returnValue = false : e.preventDefault();
  			document.getElementById('JweixinTip').style.display='block';
        $("#JweixinTip").show();
    })
		$("#JweixinTip").click(function(){
      $(this).hide();
		})
	}
}
